package com.zhaotianhao.check.userserver.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhaotianhao.check.userserver.entity.City;
import com.zhaotianhao.check.userserver.mapper.CityMapper;
import com.zhaotianhao.check.userserver.service.ICityService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Z-7
 * @since 2022-04-01
 */
@Service
public class CityServiceImpl extends ServiceImpl<CityMapper, City> implements ICityService {


    /**
     * 三级联动查询
     *
     * @param pid
     * @return
     */
    @Override
    public List<City> selectAll(int pid) {
        return getBaseMapper().getCities(pid);
    }

    /**
     * 三级联动 递归
     *
     * @param pid
     * @return
     */
    @Override
    public List<City> getCityTree(Integer pid) {

        // 查询所有数据
        List<City> list = list();
        // 通过stream流 过滤出父级id为传入id的 并转为集合 === 省
        List<City> proList = list.stream().filter(a -> Objects.equals(a.getPid(), pid)).collect(Collectors.toList());
        // 省 循环设置子集
        proList.forEach(pro->pro.setChildren(getChildren(list,pro.getId())));
        return list;
    }

    /**
     *
     * @param list 所有数据
     * @param pid 父级id
     * @return 子集
     */
    public List<City> getChildren(List<City> list, Integer pid) {
        // 通过stream流 过滤出父级id为传入id的 并转为集合
        List<City> childrenList = list.stream().filter(a -> Objects.equals(a.getPid(), pid)).collect(Collectors.toList());
        // 通过stream流 过滤出上边子集中 类型不是县的
        List<City> collect = childrenList.stream().filter(a -> a.getType() != 3).collect(Collectors.toList());
        // 判断 如果collect为空 则是最后一级 没有子集
        if (CollectionUtil.isEmpty(collect)) {
            return childrenList;
        }
        // 否则 继续调用本方法设置子集
        childrenList.forEach(child->child.setChildren(getChildren(list,child.getId())));
        return childrenList;
    }
}
